package accounts

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"minititok/Services"
	"net/http"
	"strconv"
)

func Login(c *gin.Context) {
	var body struct {
		Username string `json:"username" binding:"required"`
		Password string `json:"password" binding:"required"`
	}

	if err := c.ShouldBindJSON(&body); err != nil {
		_ = c.Error(fmt.Errorf("请求错误:" + err.Error()))
		c.JSON(http.StatusBadRequest, gin.H{"customMessage": "参数不合法"})
		return
	}

	user, err := Services.FindUserByUsername(body.Username)

	if err != nil {
		_ = c.Error(fmt.Errorf("用户不存在:" + err.Error()))
		c.JSON(http.StatusBadRequest, gin.H{"customMessage": "用户不存在"})
		return
	}

	if Perr := Services.CheckPassword(body.Password, user.Password); Perr != true {
		_ = c.Error(fmt.Errorf("密码错误:%w", err))
		c.JSON(http.StatusBadRequest, gin.H{"customMessage": "密码错误"})
		return
	}

	uuid := user.UID
	accessToken, errAc := jwtManager.CreateAccessToken(strconv.Itoa(uuid))
	refreshToken, errRf := jwtManager.CreateRefreshToken(strconv.Itoa(uuid))
	if errAc != nil || errRf != nil {
		_ = c.Error(fmt.Errorf("token生成错误:%w", err))
		c.JSON(http.StatusBadRequest, gin.H{"customMessage": "Token生成失败"})
		return
	}
	c.JSON(200, gin.H{
		"access_token":  accessToken,
		"refresh_token": refreshToken,
		"expires_in":    7200,
	})
}

func refresh(c *gin.Context) {
	var body struct {
		RefreshToken string `json:"refresh_token"`
	}

	if err := c.ShouldBindJSON(&body); err != nil {
		_ = c.Error(fmt.Errorf("请求错误:" + err.Error()))
		c.JSON(http.StatusBadRequest, gin.H{"customMessage": "参数不合法"})
		return
	}

	payload, err := jwtManager.VerifyToken(body.RefreshToken)
	if err != nil {
		_ = c.Error(fmt.Errorf("刷新token验证失败:" + err.Error()))
		c.JSON(http.StatusBadRequest, gin.H{"customMessage": "身份验证错误"})
		return
	}
	uuid := payload["uuid"].(string)
	acToken, err := jwtManager.CreateAccessToken(uuid)
	if err != nil {
		_ = c.Error(fmt.Errorf("Token创建失败:" + err.Error()))
		c.JSON(http.StatusBadRequest, gin.H{"customMessage": "Token错误,请重试"})
		return
	}
	c.JSON(200, gin.H{
		"access_token": acToken,
		"expires_in":   7200,
	})
}

func GetUserInfo(c *gin.Context) {
	user, exists := c.Get("user") // 由 JWT 中间件设置
	if !exists {
		_ = c.Error(fmt.Errorf("token与上下文用户不符,未知请求"))
		c.JSON(http.StatusUnauthorized, gin.H{"customMessage": "token验证不通过"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"user": user})
}
